﻿/*
作者：张雁鸿
时间：2010-5-23
版本：0.1

Author: Zhang Yanhong
Date: 2010-5-23
Version: 0.1


测试代码：
var x = new StringBuilder(1, 2, 3, new Date());
x.append("b");
x.append("c");
x.append("d", "f").append("e", "q");
//alert(x.toString());

var s = String.format("test:{0},{1},{2},{3}", new Date(), 23, "hello", "sss");
//alert(s);
*/



//字符串构建，减少加号链接字符串的开销。
//参数任意多
function StringBuilder() {
    this._buffer_ = new Array();
    if (arguments.length > 0) {
        for (var i = 0; i < arguments.length; i++) {
            this._buffer_.push(arguments[i]);
        }
    }
    if (StringBuilder._initialized == undefined) {
        //添加字符串，参数任意多
        StringBuilder.prototype.append = function() {
            if (arguments.length > 0) {
                for (var i = 0; i < arguments.length; i++) {
                    this._buffer_.push(arguments[i]);
                }
            }
            return this;
        }
        //重写toString返回链接结果。
        StringBuilder.prototype.toString = function() {
            return this._buffer_.join("");
        }
        StringBuilder._initialized = true;
    }
}

//格式化字符串，借鉴自.net下格式化机制
String.format = function(s) {
    if (arguments.length == 1) return s;
    for (var i = 0; i < arguments.length - 1; i++) {
        var e = "\\{" + i + "\\}";
        e = new RegExp(e, "gi");
        s = s.replace(e, arguments[i + 1]);
    }
    return s;
}

